class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        h = ListNode(-1)
        h.next = head
        pre = h
        left = head
        right = head.next
        while left and right:
            left.next = right.next
            pre.next = right
            right.next = left
            pre = left
            left = pre.next
            if left:
                right = left.next
        return h.next


a = ListNode(1)
a.next = ListNode(2)
a.next.next = ListNode(3)
a.next.next.next = ListNode(4)

b = Solution().swapPairs(a)
while b:
    print(b.val)
    b = b.next
